package controllers

import (
	"book-management-system/models"
	"book-management-system/repositories"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

func GetBooks(c *gin.Context) {
	books, err := repositories.GetAllBooks()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, books)
}

func CreateBook(c *gin.Context) {
	var book models.Book
	if err := c.ShouldBindJSON(&book); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := repositories.CreateBook(&book); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, book)
}

//	func UpdateBook(c *gin.Context) {
//		var book models.Book
//		if err := c.ShouldBindJSON(&book); err != nil {
//			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
//			return
//		}
//
//		if err := repositories.UpdateBook(repositories.DB, &book); err != nil { // 传递数据库对象
//			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
//			return
//		}
//
//		c.JSON(http.StatusOK, book)
//	}
func UpdateBook(c *gin.Context) {
	var input struct {
		Name     string `json:"name" binding:"required"`
		Quantity int    `json:"quantity" binding:"required"`
	}

	// 绑定输入的数据，注意这里只接受 Name 和 Quantity
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	id := c.Param("id")

	// 查找现有的书籍
	existingBook, err := repositories.GetBookByID(repositories.DB, id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.JSON(http.StatusNotFound, gin.H{"error": "Book not found"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 更新书名和数量，保持 ISBN 不变
	existingBook.Name = input.Name
	existingBook.Quantity = input.Quantity

	// 保存更新后的书籍
	if err := repositories.UpdateBook(repositories.DB, existingBook); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, existingBook)
}

func DeleteBook(c *gin.Context) {
	id := c.Param("id")

	if err := repositories.DeleteBook(id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Book deleted"})
}
